<?php

//网站前台
class IndexController extends FrontBaseC {

    //网站首页
    public function actionIndex() {
        
        $CategoryModel = new CategoryModel();
        $cid = Yii::app()->request->getParam('cid');
        $GoodsModel = new GoodsModel();

        //首页分页
        if ((isset($_GET['page']) || isset($_GET['sort'])) && (!isset($_GET['cid']))) {
            //有当前页码 或者有 排序字段的  并且CID为空
            $sort = isset($_GET['sort']) ? $_GET['sort'] : "default";
            $home_goods = $GoodsModel->getHomeGoods(ConfigModel::model()->getConfig('home_num'), true, $sort);
            if ($sort == 'default') {
                $home_goods[0] = $GoodsModel->orderRandomForStartTime($home_goods[0]);
            }
            $sortList = array('add_time', 'sales', 'promo_price');
            if (isset($_GET['sort']) && in_array($_GET['sort'], $sortList)) {
                $list = "/front/index/index/sort/{$_GET['sort']}/page/*.html";
                $index = "/front/index/index/sort/{$_GET['sort']}.html";
            } else {
                $list = "/front/index/index/page/*.html";
                $index = "/index.html";
            }
            $page_model = self::page($home_goods[1]->itemCount, $home_goods[1]->getLimit(), $home_goods[1]->currentPage + 1, array('isrule' => true, 'rule' => array('index' => $index, 'list' => $list)));
            $pages = $page_model->show();
            $this->render('noTitleGoodlist', array(
                'home_goods' => $home_goods[0],
                'pages' => $pages,
            ));
            return;
        }

        //各类目上期热卖
        if (isset($_GET['cid']) && isset($_GET['timeico']) && $_GET['timeico'] == 'y') {
            //cid不为空 并且 timeico == y的
            $home_goods = $GoodsModel->getCatYesterdayGoods(ConfigModel::model()->getConfig('home_num'));
            $page_model = self::page($home_goods[1]->itemCount, $home_goods[1]->getLimit(), $home_goods[1]->currentPage + 1, array('isrule' => true, 'rule' => array('index' => self::U('front/index/index', array('cid' => (int) $_GET['cid'], 'timeico' => 'y')), 'list' => '/front/index/index/cat/' . (int) $_GET['cid'] . '/timeico/y/page/*.html')));
            $pages = $page_model->show();
            $this->render('goodlist', array(
                'home_goods' => $home_goods[0],
                'pages' => $pages,
                'cid' => (int) $_GET['cid'],
                'timeico' => 'y',
            ));
            return;
        }

        //各类目数据
        if (isset($_GET['cid']) && $cid) {

            $this->layout = 'theme.views.layouts.NoCatContent';
            $cid = (int) $_GET['cid'];
            //cid不为空的
            $home_goods = $GoodsModel->getCatGoods(ConfigModel::model()->getConfig('home_num'));
            $page_model = self::page($home_goods[1]->itemCount, $home_goods[1]->getLimit(), $home_goods[1]->currentPage + 1, array('isrule' => true, 'rule' => array('index' => self::U('front/index/index', array('cid' => $cid)), 'list' => '/front/index/index/cid/' . $cid . '/page/*.html')));
            $pages = $page_model->show();
//            $this->render('double-11-cat', array(
//                'home_goods' => $home_goods[0],
//                'pages' => $pages,
//                'cid' => $_GET['cid'],
//                'timeico' => 'td',
//            ));
            $this->render('goodlist', array(
                'home_goods' => $home_goods[0],
                'pages' => $pages,
                'cid' => $cid
            ));
            return;
        }
        //先加上去取首页banner
        $adList = AdvertisingModel::getListForType(1);
        $this->assign('adList', $adList);
        /*
         * 首页瀑布流处理
         * 往缓存中存入goods_ID数组
         */
        $home_goods = $GoodsModel->getHomeGoods(ConfigModel::model()->getConfig('home_num'), 'GoodsModel_Goodsids_Goodsids');
        $page_model = self::page($home_goods[1]->itemCount, $home_goods[1]->getLimit(), $home_goods[1]->currentPage + 1, array('isrule' => true, 'rule' => array('index' => '/index.html', 'list' => '/front/index/index/page/*.html')));
        $pages = $page_model->show(); //给用户看的分页链接

        $this->render('index', array(
            'custom_blocks' => CustomBlockModel::model()->getOnBlock(),
            'pages' => $pages,
            'page' => 0,
        ));
    }

    /**
     * ajax 根据ID获取商品
     */
    public function actionAjaxGoods() {
        $key = 'GoodsModel_Goodsids_Goodsids';
        $page = (int) $_GET['page'] > 0 ? $_GET['page'] : 0; //第几页
        $page_size = (int) Yii::app()->params->page_size['sault_index']; //每页的个数
        $ids = Yii::app()->cache->get($key);
        if (!empty($ids[0])) {
            $ids = $ids[0];
            $ids_get = array_slice($ids, $page * $page_size, $page_size);   //取前面的 N个元素
        } else {
            return '';
        }
        /*
          $_GET['page'] = (int) $_GET['page'] + 1;
          $page_size = (int) Yii::app()->params->page_size['sault_index']; //每页的个数
          $countPage = ceil(ConfigModel::model()->getConfig('home_num') / $page_size);
          if ($_GET['page'] > $countPage) {
          return '';
          }
          $data = GoodsModel::model()->getHomeGoods($page_size);
          if (empty($data) || empty($data[0])) {
          return '';
          }
          $ids_get = $data[0];
         */
        foreach ($ids_get as $good) {
            if ((int) $_GET['page'] < 2) {
                $lazyload = true;
            } else {
                $lazyload = false;
            }
            include $this->getViewFile('../lib/nohfgoodlist');
        }
    }

    /**
     * 首页ajax请求 秋冬新款
     * @author SongXing
     */
    public function actionAjax() {
        $GoodsModel = new GoodsModel();
        $type = !empty($_GET['type']) ? $_GET['type'] : "homegoods"; //商品类型
        $page = (int) $_GET['page'] < 1 ? $_GET['page'] : 1; //第几页
        if ($type == "recommendgoods") {
            $goods = $GoodsModel->getRecommendGoods();
        }
        foreach ($goods as $good) {
            include $this->getViewFile('../lib/nohfgoodlist');
        }
    }

    //用于广告展示
    public function actionNoHF() {
        $this->layout = 'theme.views.layouts.FrontNoHFContent';
        $jkj = array(
            array(
                'label' => '9.9专区',
                'url' => array('/front/cat/jj'),
                'itemOptions' => array('class' => 'jkj'),
            ),);
        $this->catMenus = CMap::mergeArray($jkj, $this->catMenus);
        $this->catMenusFix = array(
            array(
                'label' => '女装',
                'url' => array('/front/index/index/', 'cid' => '1'),
                'itemOptions' => array('class' => 'womens'),
            ),
            array(
                'label' => '男装',
                'url' => array('/front/index/index/', 'cid' => '2'),
                'itemOptions' => array('class' => 'man'),
            ),
            array(
                'label' => '母婴',
                'url' => array('/front/index/index/', 'cid' => '3'),
                'itemOptions' => array('class' => 'gravida-baby'),
            ),
            array(
                'label' => '鞋类',
                'url' => array('/front/index/index/', 'cid' => '4'),
                'itemOptions' => array('class' => 'shoes'),
            ),
            array(
                'label' => '居家',
                'url' => array('/front/index/index/', 'cid' => '5'),
                'itemOptions' => array('class' => 'furnishing'),
            ),
            array(
                'label' => '美食',
                'url' => array('/front/index/index/', 'cid' => '6'),
                'itemOptions' => array('class' => 'fine-food'),
            ),
            array(
                'label' => '配饰',
                'url' => array('/front/index/index/', 'cid' => '7'),
                'itemOptions' => array('class' => 'bags'),
            ),
            array(
                'label' => '数码',
                'url' => array('/front/index/index/', 'cid' => '9'),
                'itemOptions' => array('class' => 'maquillage'),
            ),
            array(
                'label' => '美妆',
                'url' => array('/front/index/index/', 'cid' => '8'),
                'itemOptions' => array('class' => 'digital'),
            ),
            array(
                'label' => '文体',
                'url' => array('/front/index/index/', 'cid' => '10'),
                'itemOptions' => array('class' => 'sport'),
            ),
            array(
                'label' => '精品推荐',
                'url' => array(''),
                'itemOptions' => array('class' => 'jp-title', 'href' => "#"),
            ),
            array(
                'label' => '京东专区',
                'url' => array('/front/cat/jd'),
                'itemOptions' => array('class' => 'jd'),
            ),
            array(
                'label' => '秋冬新款',
                'url' => array('/front/index/qing'),
                'itemOptions' => array('class' => 'qing'),
            ),
            array(
                'label' => '9.9专区',
                'url' => array('/front/cat/jj'),
                'itemOptions' => array('class' => 'jj'),
            ),
        );


        $GoodsModel = new GoodsModel();

        $home_goods = $GoodsModel->getHomeGoods(ConfigModel::model()->getConfig('home_num'));
        $recommend_goods = $GoodsModel->getRecommendGoods();

        $this->render('nohf', array(
            'custom_blocks' => CustomBlockModel::model()->getOnBlock(),
            'home_goods' => $GoodsModel->orderRandomForStartTime($home_goods[0]),
            'pages' => $home_goods[1],
            'page' => isset($_GET['page']) ? $_GET['page'] : 1,
            'recommend_goods' => $GoodsModel->orderRandomForStartTime($recommend_goods),
        ));
    }

    //反季清仓
    public function actionQing() {
        $this->layout = 'theme.views.layouts.qingContent';
        SeoWord::setWord($this, 'getCatSeo', 'qing');
        $time = time();
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => array('LT', 10),
            //'level' => 1,
            'status' => 1,
            'is_best' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        $recommend_goods = GoodsModel::model()->getGoodsList($where, 0, false, 'start_time DESC ,listorder DESC, sales DESC');
        $this->assign('home_goods', $recommend_goods);
        $this->render('qing');
    }

    //御寒专场
    public function actionZhuanChang() {
        $this->layout = 'theme.views.layouts.qingContent';
        $this->description = '';
        $this->keywords = '';
        $this->title = '1折网活动专场 - 淘牛品1折网官网';
        //↓↓↓↓↓↓↓↓↓↓↓↓↓↓御寒专场↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//        $start_time = strtotime("2014-10-21 00:00:00") ;
//        $end_time = strtotime("2014-10-24 00:00:00") ;
//        $where = array(
//            'item_type' => array('LT', 10),
//            'status' => 1,
//            'is_best' => 1,
//            'start_time' => array('LT', $start_time),
//            'end_time' => array('GT', $end_time),
//        );
//        $recommend_goods = GoodsModel::model()->getGoodsList($where, 0, false, 'start_time DESC ,listorder DESC, sales DESC');
//        $this->assign('home_goods', $recommend_goods);
        //↑↑↑↑↑↑↑↑↑↑↑↑↑↑御寒专场↑↑↑↑↑↑↑↑↑↑↑↑↑↑
        /* ↓↓↓↓↓↓↓↓↓↓↓↓↓↓美食专场↓↓↓↓↓↓↓↓↓↓↓↓↓↓ */
        $where = array(
            'start_time' => array('LT', strtotime("2014-10-28 00:00:00")),
            'end_time' => array('GT', time()),
        );
        $cacheKey = 'front_actionZhuanChang';
        $home_goods = GoodsModel::model()->getSpecialGoods(2, 0, $where,false,'default',true,$cacheKey);
        foreach ($home_goods as $k => $rs) {
            $home_goods[$k]['sales_str'] = "已售<span class='font-arial'>{$rs['sales']}</span>件";
        }
        $this->assign('home_goods', $home_goods);
        /* ↑↑↑↑↑↑↑↑↑↑↑↑↑↑美食专场↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

        $this->render('food');
    }

    //天猫专场
    public function actionTmall() {
        SeoWord::setWord($this, 'getCatSeo', 'tmall');
        $time = time();
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        $page = (int) $_GET['page'];
        $tmall = GoodsModel::model()->getGoodsList($where, ConfigModel::model()->getConfig('home_num'), $page);
        $page_model = self::page($tmall[1]->itemCount, $tmall[1]->getLimit(), $tmall[1]->currentPage + 1);
        $pages = $page_model->show();

        $this->assign('home_goods', $tmall[0]);
        $this->assign('pages', $pages);
        $this->render();
    }

    //积分兑换
    public function actionScore() {
        $time = time();
        SeoWord::setWord($this, 'getCatSeo', 'jifen');
        $objCDbCriteria = new CDbCriteria(array(
            'condition' => 'status = :status AND start_time <= :start_time AND (end_time = 0 or end_time >= :end_time)',
            'params' => array(
                'status' => RedeemModel::STATUS_APPROVE,
                'start_time' => $time,
                'end_time' => $time,
            ),
            'order' => 'listorder desc,integral asc',
        ));

        $data = RedeemModel::model()->findAll($objCDbCriteria);
        $arr_data = array();
        $arr_data_exchange = array();
        $time = time();
        $this->assign('time', $time); //现在的时间       
        //秒光的跟未开始兑换的排序到后面
        foreach ($data as $key => $objData) {
            $sum = $objData->RecordQuantum;
            if ($objData->quantum <= $sum) {
                $arr_data[$key] = $objData;
                unset($data[$key]);
                continue;
            }
            //还未开始
            if ($objData->exchange_start_time > $time) {
                $arr_data_exchange[$key] = $objData;
                unset($data[$key]);
            }
        }
        $data = array_merge_recursive($data, $arr_data_exchange, $arr_data);

        if (Yii::app()->user->id) {
            $this->assign('user', Yii::app()->user->getInfo());
            $count = RedeemRecordsModel::model()->count(RedeemModel::model()->where(array('uid' => Yii::app()->user->id)));
            $this->assign('count', $count);
        }
        //设置弹出层 出现3次之后,1年内不再出现
        $value = $this->getCookie('score_convert');
        if (empty($value) || $value < 4) {
            $value+=1;
            $this->setCookie('score_convert', $value, time() + 60 * 60 * 24 * 30 * 12);
            $result = true;
        } else
            $result = false;

        $this->assign('data', $data);
        $this->assign('result', $result);
        $this->render('score');
    }

    /**
     * 网站地图
     */
    public function actionSiteMap() {
        //今日特惠 显示数目 尽量写大
        $home_goods_num = 2000;
        $GoodsModel = new GoodsModel();
        $CustomBlockModel = new CustomBlockModel();
        $custom_blocks = $CustomBlockModel->getOnBlock();     //首页 "每日精选"的商品
        $home_goods = $GoodsModel->getHomeGoods($home_goods_num);   //首页 "今日特惠"的商品
        $recommend_goods = $GoodsModel->getRecommendGoods();    //首页 "秋冬新款"的商品
        $yesterday_goods = $GoodsModel->getCatYesterdayGoods($home_goods_num); //"上期热卖"的商品
        $tomorrow_goods = $GoodsModel->getTomorrowGoods($home_goods_num);     //"下期预告"的商品
        //var_dump($custom_blocks);
        $this->render('sitemap', array(
            'custom_blocks' => $custom_blocks,
            'home_goods' => $home_goods[0],
            'recommend_goods' => $recommend_goods,
            'yesterday_goods' => $yesterday_goods[0],
            'tomorrow_goods' => $tomorrow_goods[0],
        ));
    }

    //标签
    public function actionTag() {
        $tag = Yii::app()->request->getParam('tag');
        if (empty($tag)) {
            $this->error('标签不能为空！');
        }
        $model = TagsContentModel::model();
        $info = TagsModel::model()->find($model->where(array('tag' => $tag)));
        if (empty($info)) {
            $this->error('该标签不存在！');
        } else {
            //点击数
            $info->hits += 1;
            $info->save();
        }
        $time = time();
        $where = array(
            'tag' => $tag,
            't.start_time' => array('LT', $time),
            't.end_time' => array('EGT', $time),
            'order' => 'updatetime desc', //GoodsModel.view desc,
        );
        //分页
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        //分页数
        $limit = 20;
        $criteria = $model->where($where);
        //信息总数
        $count = $model->count($criteria);
        //分页
        $page = self::page($count, $limit, $pageId);
        //查询信息
        $criteria->limit = $page->listRows;
        $criteria->offset = $page->firstRow;
        $dataList = array();
        $data = $model->with('GoodsModel')->findAll($criteria);
        if (empty($data)) {
            $this->error('该标签下暂时没有数据！');
        }
        $cats = CategoryModel::model()->getList();
        foreach ($data as $rs) {
            $dataList[] = GoodsModel::convertGood($rs->GoodsModel, $cats);
        }
        $this->assign("Page", $page->show());
        $this->assign('data', $dataList);
        $this->assign('count', $count);
        $this->assign('tag', $tag);
        $this->render();
    }

    //今日特惠 的所有链接
    public function actionSc() {
        $this->layout = 'theme.views.layouts.FrontNoHeaderContent';
        //今日特惠 显示数目 尽量写大
        $home_goods_num = 2000;
        $GoodsModel = new GoodsModel();
        $home_goods = $GoodsModel->getHomeGoods($home_goods_num);   //首页 "今日特惠"的商品
        //var_dump($custom_blocks);
        $this->render('sc', array(
            'home_goods' => $home_goods[0],
        ));
    }




    /**
     * 美丽说模仿/自己写CSS
     * @return [type] [description]
     */
    public function actionArticlesList(){
        $data = ContentArticlesModel::model()->findAll();

 
        $objModel = new ContentArticlesModel('search');

        $objModel->unsetAttributes();


        if( isset( $_GET['ContentArticlesModel'] ) )
        {
            $objModel->attributes = $_GET['ContentArticlesModel'];
        }


        $objCriteria = $objModel->createSearchCriteria(); 

        $objPager = new CPagination($objModel->count($objCriteria));
        $objPager->pageSize = 20;
        $objPager->applyLimit($objCriteria);

        $objSort = new CSort('ContentArticlesModel');
        $objSort->defaultOrder = 'createtime DESC';
        $objSort->applyOrder($objCriteria);
        
        $objModels = $objModel->findAll($objCriteria);

        $this->assign('pages', $objPager);
        $this->assign('sort', $objSort);
        $this->assign('model', $objModel); 
        $this->assign('models', $objModels);

        $this->render();
    }

    public function actionArticlesDetail(){
        $id = yii::app()->request->getParam('id');
        $data = ContentArticlesModel::model()->findByPk($id);
        if($data === false){
            $this->error('请求错误');
        }
        $this->assign('data', $data);
        $this->render();
    }


    /*
    public function actionCeshi(){
        $datas = CheatsModel::model()->findAll();
        foreach ($datas as $key => $data) {
            $content = $data->content . '<br/>';
            if(!empty($data->img1)){
                $content .= "<img style='width:200px;height:200px' src='http://file.mamijie.com/{$data->img1}'/>";
            }
            if(!empty($data->img2)){
                $content .= "<img style='width:200px;height:200px' src='http://file.mamijie.com/{$data->img2}'/>";
            }
            if(!empty($data->img3)){
                $content .= "<img style='width:200px;height:200px' src='http://file.mamijie.com/{$data->img3}'/>";
            }
            $d = array(
                'title' => $data->title,
                'catid' => 1,
                'keywords' => $data->title,
                'description' => $data->title,
                'content' => $content,
                'createtime' => $data->add_time,
                'is_hot' => 1,
                'admin_id' => $data->admin_id,
                'admin_username' => $data->admin_name,
                'uid' => $data->uid,
                'username' => $data->username,
            );
            $model = new ContentArticlesModel();
            $model->attributes = $d;
            $model->save();
        }
    }
    */




    /**
     * 妈咪特惠控制器
     * @return [type] [description]
     */
    public function actionMomdiscount(){
        $this->layout = 'theme.views.layouts.FrontMomdiscountContent';
        $this->render();
    }

    /**
     * 测试修改图片控制器
     * @return [type] [description]
     */
/*    public function actionUpdateimg(){
        $datas = GoodsModel::model()->findAll();
        foreach($datas as $data){
            $strimg = $data->product_img;
            if(!stripos($strimg,'_300x300.jpg')){
                $data->product_img = $strimg . '_300x300.jpg';
                $data->save(false,array('product_img'));
            }
        }
        echo 'ok';
    }*/    

}
